import axios from 'axios'
import Storage from '@/commons/storage'
import Message from "@/components/message"

// create an axios instance
const service = axios.create({
    baseURL: import.meta.env.VUE_APP_API_URL,
    headers: {
        'X-Requested-With': 'XMLHttpRequest'
    },
    withCredentials: false,
    timeout: 30000
})

// request interceptor
service.interceptors.request.use(
    config => {
        if (Storage.get("token")) {
            config.headers['X-Token'] = "1b0679be72ad976ad5d491ad57a5eec0"
            config.headers['Authorization'] = 'Bearer ' + Storage.get("token")
        }
        return config
    },
    error => {
        Message.toast(error.message || '请求错误')
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        let res = response.data
        let header = response.headers['content-disposition']
        
        if (header != undefined && header.split(';')[0] == 'attachment') {
            res = response
        }
        
        if (response.status !== 200) {
            Message.toast(res.message || '请求失败')
            return Promise.reject(new Error(res.message || '请求失败'))
        } else {
            return Promise.resolve(res)
        }
    },
    error => {
        console.log('err' + error)
        Message.toast(error.message || '网络错误')
        return Promise.reject(error)
    }
)

const Request = {}

Request.http = (url, data = {}, method = 'GET', headers = { 'content-type': 'application/x-www-form-urlencoded' }, responseType = null) => {
    if (headers['content-type'] === 'application/x-www-form-urlencoded') {
        return service({ url: url, params: data, method: method, headers: headers, responseType: responseType })
    } else {
        return service({ url: url, data: data, method: method, headers: headers, responseType: responseType })
    }
}

Request.getForm = (url, data = {}) => {
    return Request.http(url, data)
}

Request.postForm = (url, data = {}) => {
    return Request.http(url, data, 'POST')
}

Request.getJson = (url, data = {}) => {
    return Request.http(url, data, 'POST', { 'content-type': 'application/json' })
}

Request.postJson = (url, data = {}) => {
    console.log('POST request to:', url) // 简单的日志输出
    return Request.http(url, data, 'POST', { 'content-type': 'application/json' })
}

Request.imp = (url, data = {}) => {
    return Request.http(url, data, 'POST', { 'Content-Type': 'multipart/form-data' })
}

Request.exp = (url, data = {}) => {
    return Request.http(url, data, 'POST', { 'content-Type': 'application/json' }, 'blob')
}

export default Request